package entry;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.SneakyThrows;
import market.bean.Market;
import market.dao.MarketMapper;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.List;


@WebServlet("/")
public class Entry extends HttpServlet {
    @SneakyThrows
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //今天主要讲了请求头和响应头的一些内容，还讲了一点文件上传和文件下载
        String curOrigin = req.getHeader("Origin");
        System.out.println(curOrigin);
        //在这里获取请求的参数
        //传参有page，limit，username，sort，order这几个值，
        //这几个值好费劲啊，封装成对象吧，很酷
        //这里其实可以尝试自己写反射的，但是，，懒惰，，
        SqlValues sqlValues=new SqlValues();
//        BeanUtils.copyProperties(sqlValues,req.getParameterMap());
        GetSqlValue.getSqlValues(sqlValues,req.getParameterMap());
        sqlValues.offset= sqlValues.page*sqlValues.limit;

        //请求数据库，获取数据
        SqlSessionFactory sqlSessionFactory=new SqlSessionFactoryBuilder().build(new FileInputStream(Resources.getResourceAsFile("my_batis.xml")));
        SqlSession sqlSession=sqlSessionFactory.openSession();
        MarketMapper marketMapper=sqlSession.getMapper(MarketMapper.class);
        String username=req.getParameter("username");
        List<Market> markets=marketMapper.getUsers(sqlValues,username);


        System.out.println(markets);
        //这里主要进行练习一下请求头的相关内容
        resp.setHeader("Access-Control-Allow-Origin", curOrigin);
        resp.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, PUT");


        resp.getWriter().println(new ObjectMapper().writeValueAsString(markets));
    }
}
